//
//  NSObject+Category.m
//  VICategory
//
//  Created by MN on 2022/8/19.
//

#import "NSObject+Category.h"

@implementation NSObject (Category)
- (NSString *)tt_className{
    return NSStringFromClass([self class]);
}

+ (NSString *)tt_className{
    return NSStringFromClass([self class]);
}

- (void)openSystemSettings{
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if (@available(iOS 11.0, *)) {
        if ([[UIApplication sharedApplication] canOpenURL:url]){
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        }
    } else {
        if ([[UIApplication sharedApplication] canOpenURL:url]){
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
            } else {
                [[UIApplication sharedApplication] openURL:url];
            }
        }
    }
}
/// 获取缓存
- (NSString *)getCacheSize {
    //获取文件管理器对象
    NSFileManager * fileManger = [NSFileManager defaultManager];
    //获取缓存沙盒路径
    NSString * fileCachePath =  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    //获取到该缓存目录下的所有子文件（只是文件名并不是路径，后面要拼接）
    NSArray * subFilePath = [fileManger subpathsAtPath:fileCachePath];
    //先定义一个缓存目录总大小的变量
    CGFloat fileTotalSize = 0;
    for (NSString * fileName in subFilePath) {
        //拼接文件全路径（注意：是文件）
        NSString * filePath = [fileCachePath stringByAppendingPathComponent:fileName];
        //获取文件属性
        NSDictionary * fileAttributes = [fileManger attributesOfItemAtPath:filePath error:nil];
        //根据文件属性判断是否是文件夹（如果是文件夹就跳过文件夹，不将文件夹大小累加到文件总大小）
        if ([fileAttributes[NSFileType] isEqualToString:NSFileTypeDirectory]) continue;
        //获取单个文件大小,并累加到总大小
        fileTotalSize += [fileAttributes[NSFileSize] floatValue];
    }
    //将字节大小转为MB，然后传出去
    return [NSString stringWithFormat:@"%.2lfMB",fileTotalSize/1024/1024];
}

- (NSString *)getAppVersion {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}
- (NSString *)getAppName {
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString *appName = [infoDict valueForKey:@"CFBundleDisplayName"];
    if (!appName) appName = [infoDict valueForKey:@"CFBundleName"];
    if (!appName) appName = [infoDict valueForKey:@"CFBundleExecutable"];
    return appName;
}

+ (UIViewController *)getTopController {
    UIViewController *rootVc = [UIApplication sharedApplication].delegate.window.rootViewController;
    return [self topController:rootVc];
}

+ (UIViewController *)topController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* nav = (UINavigationController*)rootViewController;
        return [self topController:nav.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topController:presentedViewController];
    } else {
        return rootViewController;
    }
}

/// 刷新缓存
- (void)alertRefreshCache:(void (^) (void))refreshBlock {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        __block BOOL is = YES;
        while (is) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([[UIView getTopController] isKindOfClass:[self class]]) {
                    is = NO;
                    refreshBlock();
                }
            });
            sleep(1);
        }
    });
}

- (NSAttributedString *)attributedText:(NSArray *)strings colors:(NSArray *)colors{

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
    for (int i= 0; i < strings.count; i++) {
        NSAttributedString *attr = [[NSAttributedString alloc] initWithString:strings[i]
                                                                   attributes:@{NSForegroundColorAttributeName : colors[i]}];
        [attributedString appendAttributedString:attr];
    }
    return attributedString;
  
}

// 读取本地JSON文件
- (NSArray *)vi_readLocalFileWithName:(NSString *)name{
    // 获取文件路径
    NSBundle *currentBundle = [NSBundle bundleForClass:self.class];

    NSString *path = [currentBundle pathForResource:name ofType:@"json"];
    // 将文件数据化
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    // 对数据进行JSON格式化并返回字典形式
    return [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
}

+ (void)vi_userDefaultsSave:(nullable id)object key:(NSString *)key{
    [[NSUserDefaults standardUserDefaults] setValue:object forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)vi_userDefaultsSave:(nullable id)object key:(NSString *)key{
    [NSObject vi_userDefaultsSave:object key:key];
}
@end
